const express = require("express");
const goods_router = express.Router();
const db = require("../config");

/* 获取所有商品 */
goods_router.get('/getALlGoods', (req, res) => {
    const sql = "SELECT g.*,s.size,c.color FROM db_goods g JOIN db_size s ON s.goodsId = g.id JOIN db_color c ON c.goodsId = g.id WHERE g.state=1;";
    db.query(sql, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("获取商品失败，请重试");
        res.send({
            status: 0,
            message: "获取商品成功",
            data: result
        })
    })
});

/* 获取指定商品 */
goods_router.get('/getAGoods', (req, res) => {
    const sql = "SELECT g.*,s.size,c.color FROM db_goods g JOIN db_size s ON s.goodsId = g.id JOIN db_color c ON c.goodsId = g.id WHERE g.state=1;";
    db.query(sql, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("获取商品失败，请重试");
        res.send({
            status: 0,
            message: "获取商品成功",
            data: result
        })
    })
});

/* 增加商品 */
goods_router.post('/AddGoods', async (req, res) => {
    const { name, description, category, imgSrc, price, DiscountPrice, size = [], color = [], storeId = 1 } = req.body;
    const goodsSql = `INSERT INTO db_goods (name, description, category, imgSrc, price, discountPrice, storeId) VALUES (?, ?, ?, ?, ?, ?, ?)`;

    db.query(goodsSql, [name, description, category, imgSrc, price, DiscountPrice, storeId], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("添加商品失败");
        const goodsId = result.insertId;

        // 将尺码和颜色的字符串根据","拆分为数组
        const sizeArray = size.split(',');
        const colorArray = color.split(',');
        console.log("尺码数组", sizeArray);

        // 处理尺码数据
        if (sizeArray.length > 0) {
            // 查询已存在的尺码
            const checkSizeSql = `SELECT size FROM db_size WHERE  goodsId = ? AND size in (?) `;
            db.query(checkSizeSql, [goodsId, sizeArray], (err, existingSizes) => {
                if (err) return res.fail(err.message);

                // 过滤出需要新增的尺码
                const existingSizeValues = existingSizes.map(item => item.size);
                const newSizes = sizeArray.filter(size => !existingSizeValues.includes(size));

                console.log("已存在的尺码", existingSizeValues, "要添加的尺码", newSizes);



                if (newSizes.length > 0) {
                    // 批量插入新尺码
                    const sizeInsertSql = `INSERT INTO db_size (goodsId, size) VALUES ?`;
                    const sizeValues = newSizes.map(size => [goodsId, size]);

                    db.query(sizeInsertSql, [sizeValues], (err) => {
                        if (err) return res.fail(err.message);
                    });
                }
            });
        }

        // 处理颜色数据
        if (colorArray.length > 0) {
            // 查询已存在的颜色
            const checkColorSql = `SELECT color FROM db_color WHERE goodsId = ? AND  color IN (?)`;
            db.query(checkColorSql, [goodsId, colorArray], (err, existingColors) => {
                if (err) return res.fail(err.message);

                // 过滤出需要新增的颜色
                const existingColorValues = existingColors.map(item => item.color);
                const newColors = colorArray.filter(color => !existingColorValues.includes(color));

                if (newColors.length > 0) {
                    // 批量插入新颜色
                    const colorInsertSql = `INSERT INTO db_color (goodsId, color) VALUES ?`;
                    const colorValues = newColors.map(color => [goodsId, color]);

                    db.query(colorInsertSql, [colorValues], (err) => {
                        if (err) return res.fail(err.message);
                    });
                }
            });
        }

        res.send({
            status: 0,
            message: "商品添加成功",
        });
    });
});

/* 修改商品信息 */
goods_router.post('/UpdateGoods', (req, res) => {
    const { name, description, category, imgSrc, price, DiscountPrice,id } = req.body;
    const sql = "update db_goods set name=?,description=?,category=?,imgSrc=?,price=?,DiscountPrice=? where id=?";
    db.query(sql, [name, description, category, imgSrc, price, DiscountPrice,id], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("修改商品信息失败，请重试");
        res.send({
            status: 0,
            message: "修改商品信息成功"
        })
    })
});

/* 修改商品尺码 */

/* 修改商品颜色 */

/* 删除商品 */
goods_router.post('/DelGoods', (req, res) => {
    const sql = "update db_goods set state=0 where id=?";
    db.query(sql, req.body.id, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("删除商品失败，请重试");
        res.send({
            status: 0,
            message: "删除商品成功"
        })
    })
});

module.exports = { goods_router };